/*!
 * Copyright (c) 2023-present StarDreamNet
 */
!function () {
    var version = "developing";

    try {
        if (!caches) {
            console.log("sw: 浏览器不支持 caches，无法对资源进行缓存");
            return;
        }
    } catch (e) {
        console.log("sw: 浏览器不支持 caches，无法对资源进行缓存");
        return;
    }


    self.addEventListener("fetch", function (event) {
        if (event.request.method !== "GET") return;
        if (event.request.url.includes("chrome-extension://")) return;
        if (event.request.url.includes("/api/")) return;
        if (event.request.headers.get("accept").includes("text/html")) return;

        event.respondWith(
            caches.open("ducksite_caches").then(async cacheDb => {
                const value = await cacheDb.match(event.request);
                if (value) { // 如缓存内存在该资源，则返回缓存内容
                    return value;
                }

                const response = await fetch(event.request);

                // 缓存该资源
                var clone = response.clone();
                cacheDb.put(event.request, clone);
                return response;
            })
        )
    });

    self.addEventListener('message', event => {
        if (event.data && event.data.type === 'SKIP_WAITING') {
            caches.delete("ducksite_caches").then(() => {
                self.skipWaiting();
            })
        }
    });
}();